package com.glowdayz.glowmee.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import com.glowdayz.common.DBHandler;
import com.glowdayz.common.DateTime;
import com.glowdayz.common.PageHandler;
import com.glowdayz.common.MultipartBox.FileInfo;
import com.glowdayz.glowmee.cmd.EventCommentCMD;

public class EventCommentDAO {
	
	static Logger logger = Logger.getLogger(EventCommentDAO.class);
	
	private static EventCommentDAO instance = null;
	
	DBHandler db = null;
	
	public static EventCommentDAO getInstance() {
		if (instance == null) {
			instance = new EventCommentDAO();
		}
		return instance;
	}
	
	public EventCommentDAO() {
		db = DBHandler.getInstance();
	}
	
	public int insertEventComment(EventCommentCMD cmd) throws SQLException {
		logger.debug("[insertEventComment] ---------- Method Start ----------");
		logger.debug("[insertEventComment][PARAM] EventCommentCMD cmd=" + cmd.toString());
		
		int result = 0;
		
		PreparedStatement pstmt = null;
		
		String sql = "INSERT INTO eventcomment("
				+ "idRegister, idAdminBoard, eventComment, isDisplay, create_date"
				+ ") VALUES (?, ?, ?, 1, ?)";
		
		pstmt = db.getPrepareStatement(sql);
		
		DBHandler.getInstance().beginTrans();
		try {
			pstmt.setInt(1, cmd.getIdRegister());
			pstmt.setInt(2, cmd.getIdAdminBoard());
			pstmt.setString(3, cmd.getEventComment());
			pstmt.setString(4, DateTime.getInstance().getNowDateTimeString());
			result = pstmt.executeUpdate();
			
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[insertEventComment] " + e.getLocalizedMessage());
			logger.error("[insertEventComment] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[insertEventComment][RETURN] result=" + result);
		logger.debug("[insertEventComment] ---------- Method End ----------");
		
		return result;
	}
	
	public int isDisplayComment(EventCommentCMD cmd) throws SQLException {
		logger.debug("[isDisplayComment] ---------- Method Start ----------");
		logger.debug("[isDisplayComment][PARAM] EventCommentCMD cmd=" + cmd.toString());
		
		int result = 0;
		
		String sql = "UPDATE eventcomment "
				+ "SET isDisplay=? "
				+ "WHERE idRegister=? AND idAdminBoard=?";
		PreparedStatement pstmt = db.getPrepareStatement(sql);
		
		try {
			pstmt.setInt(1, cmd.getIsDisplay());
			pstmt.setInt(2, cmd.getIdRegister());
			pstmt.setInt(3, cmd.getIdAdminBoard());
			
			DBHandler.getInstance().beginTrans();
			result = pstmt.executeUpdate();
			
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			DBHandler.getInstance().rollback();
			logger.error("[isDisplayComment] " + e.getLocalizedMessage());
			logger.error("[isDisplayComment] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		
		if (result > 0) {
			DBHandler.getInstance().commit();
		} else {
			DBHandler.getInstance().rollback();
		}
		
		logger.debug("[isDisplayComment][RETURN] result=" + result);
		logger.debug("[isDisplayComment] ---------- Method End ----------");
		
		return result;
	}
	
	public ArrayList<EventCommentCMD> getCommentList(int page, int count, String where) throws Exception {
		logger.debug("[getCommentList] ---------- Method Start ----------");
		logger.debug("[getCommentList][PARAM] page=" + page);
		logger.debug("[getCommentList][PARAM] count=" + count);
		logger.debug("[getCommentList][PARAM] where=" + where);
		
		ArrayList<EventCommentCMD> result = null;
		int cnt = db.getCount("eventcomment e, register r", "*", "e.idRegister=r.idRegister AND " + where);
		
		if (count == -1) {
			count = cnt;
		}
		
		String sql = "SELECT e.idRegister, r.nickName, e.idAdminBoard, e.eventComment, e.isDisplay, e.create_date "
					+ "FROM eventcomment e, register r "
					+ "WHERE e.idRegister=r.idRegister AND " + where + " "
					+ "ORDER BY e.create_date DESC "
					+ "LIMIT ?, ?";
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(sql);
		
		if (cnt == 0) {
			PageHandler.getInstance(page, cnt);
		} else {
			// 페이징 처리 --> 한 페이지에 count개씩, 페이지번호는 10개 출력
			PageHandler.getInstance(page, cnt, count, 10);
		}
		
		try {
			pstmt.setInt(1, PageHandler.getInstance().getStartRec());
			pstmt.setInt(2, PageHandler.getInstance().getPageArticleCount());
			ResultSet rs = pstmt.executeQuery();
			
			if (rs != null) {
				
				// SQL문장에 이상이 없을 경우에만 list 객체를 할당한다.
				// 이 객체가 null이라면 SQL실행에 실패한 경우이다.
				// 객체가 생성되지만, add()가 실행되지 않아서, size()값이 0이라면
				// 조건에 맞는 데이터가 없는 경우이다.
				result = new ArrayList<EventCommentCMD>();
				
				while(rs.next()) {
					int idRegister = rs.getInt(1);
					String nickName = rs.getString(2);
					int idAdminBoard = rs.getInt(3);
					String eventComment = rs.getString(4);
					int isDisplay = rs.getInt(5);
					String create_date = rs.getString(6);
					
					FileInfo image = this.getImage(idRegister);
					
					EventCommentCMD item = new EventCommentCMD(idRegister, nickName, idAdminBoard, eventComment, isDisplay, create_date, image);
					result.add(item);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error("[getCommentList] " + e.getLocalizedMessage());
			logger.error("[getCommentList] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
			}
		}
		
		if (result != null) {
			logger.debug("[getCommentList][RETURN] result_count=" + result.size());
		}
		logger.debug("[getCommentList] ---------- Method End ----------");
		
		return result;
	}
	
	/**
	 * 이벤트 리스트 xml
	 * @param page
	 * @param count
	 * @param id
	 * @return
	 */
	public ArrayList<EventCommentCMD> getCommentList(int page, int count, int id) throws Exception {
		logger.debug("[getCommentList] ---------- Method Start ----------");
		logger.debug("[getCommentList][PARAM] page=" + page);
		logger.debug("[getCommentList][PARAM] count=" + count);
		logger.debug("[getCommentList][PARAM] id=" + id);
		
		ArrayList<EventCommentCMD> result = null;
		int cnt = db.getCount("eventcomment", "*", "idAdminBoard=" + id);
		
		if (count == -1) {
			count = cnt;
		}
		
		String sql = "SELECT e.idRegister, r.nickName, e.eventComment, e.create_date "
					+ "FROM eventcomment e, register r "
					+ "WHERE e.idRegister=r.idRegister AND e.idAdminBoard=" + id + " "
					+ "ORDER BY e.create_date DESC "
					+ "LIMIT ?, ?";
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(sql);
		
		if (cnt == 0) {
			PageHandler.getInstance(page, cnt);
		} else {
			// 페이징 처리 --> 한 페이지에 count개씩, 페이지번호는 10개 출력
			PageHandler.getInstance(page, cnt, count, 10);
		}
		
		try {
			pstmt.setInt(1, PageHandler.getInstance().getStartRec());
			pstmt.setInt(2, PageHandler.getInstance().getPageArticleCount());
			ResultSet rs = pstmt.executeQuery();
			
			if (rs != null) {
				
				// SQL문장에 이상이 없을 경우에만 list 객체를 할당한다.
				// 이 객체가 null이라면 SQL실행에 실패한 경우이다.
				// 객체가 생성되지만, add()가 실행되지 않아서, size()값이 0이라면
				// 조건에 맞는 데이터가 없는 경우이다.
				result = new ArrayList<EventCommentCMD>();
				
				while(rs.next()) {
					int idRegister = rs.getInt(1);
					String nickName = rs.getString(2);
					String eventComment = rs.getString(3);
					String create_date = rs.getString(4);
					
					FileInfo image = this.getImage(idRegister);
					
					EventCommentCMD item = new EventCommentCMD(idRegister, nickName, eventComment, create_date, image);
					result.add(item);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error("[getCommentList] " + e.getLocalizedMessage());
			logger.error("[getCommentList] " + e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
			}
		}
		
		if (result != null) {
			logger.debug("[getCommentList][RETURN] result_count=" + result.size());
		}
		logger.debug("[getCommentList] ---------- Method End ----------");
		
		return result;
	}
	
	public FileInfo getImage(int idx) throws SQLException {
		String fileSql = "SELECT fileOrgName, idAttacheFile, fileSaveName, fileDir, fileSize, fileType, sortKey "
				+ "FROM attachefile "
				+ "WHERE tableName='register' AND tableKey=?";
		
		PreparedStatement pstmt = DBHandler.getInstance().getPrepareStatement(fileSql);
		FileInfo info = null;
		
		try {
			pstmt.setInt(1, idx);
			ResultSet rs = pstmt.executeQuery();
			if (rs != null) {
				while(rs.next()) {
					String fileOrgName = rs.getString(1);
					int idAttacheFile = rs.getInt(2);
					String fileSaveName = rs.getString(3);
					String fileDir = rs.getString(4);
					int fileSize = rs.getInt(5);
					String fileType = rs.getString(6);
					int sortKey = rs.getInt(7);
					
					info = new FileInfo("", idAttacheFile, fileOrgName, fileSaveName, fileDir, fileSize, fileType, sortKey);
				}
				rs.close();
				rs = null;
			}
			pstmt.close();
			pstmt = null;
		} catch (SQLException e) {
			logger.error(e.getLocalizedMessage());
			logger.error(e.getSQLState());
		} finally {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}
		return info;
	}
	
}
